#include "data_pool.h"
#include "logger.h"
#include <stdlib.h>
#include <string.h>
#include <fnmatch.h>

int data_pool_init(data_pool_t *pool, size_t max_size, event_loop_t *event_loop, db_manager_t *db_mgr) {
    if (!pool) {
        return ERROR_INVALID_PARAM;
    }

    memset(pool, 0, sizeof(data_pool_t));

    if (pthread_rwlock_init(&pool->rwlock, NULL) != 0) {
        return ERROR_THREAD_CREATE;
    }

    pool->hash_table = NULL;
    pool->max_size = max_size;
    pool->current_size = 0;
    pool->event_loop = event_loop;
    pool->db_mgr = db_mgr;
    pool->persist_to_db = (db_mgr != NULL);

    // 如果启用了数据库持久化，从数据库加载数据
    if (pool->persist_to_db) {
        data_pool_load_from_db(pool);
    }

    return SUCCESS;
}

int data_pool_load_from_db(data_pool_t *pool) {
    if (!pool || !pool->db_mgr || !pool->persist_to_db) {
        return ERROR_INVALID_PARAM;
    }

    struct load_context {
        data_pool_t *pool;
        int count;
    } context = {pool, 0};

    int callback(void *user_data, const char *key, json_t *value) {
        struct load_context *ctx = (struct load_context *)user_data;

        // 将数据添加到内存池（不触发事件，避免循环）
        pthread_rwlock_wrlock(&ctx->pool->rwlock);

        data_item_t *item = NULL;
        HASH_FIND_STR(ctx->pool->hash_table, key, item);

        if (item) {
            // 更新现有项
            json_decref(item->value);
            item->value = json_incref(value);
            item->timestamp = time(NULL);
        } else {
            // 创建新项
            item = malloc(sizeof(data_item_t));
            if (item) {
                item->key = strdup(key);
                item->value = json_incref(value);
                item->timestamp = time(NULL);

                HASH_ADD_STR(ctx->pool->hash_table, key, item);
                ctx->pool->current_size++;
            }
        }

        pthread_rwlock_unlock(&ctx->pool->rwlock);
        ctx->count++;

        return 0;
    }

    int rc = db_datapool_get_all(pool->db_mgr, callback, &context);
    if (rc == SUCCESS) {
        LOG_INFO("Loaded %d items from database into data pool", context.count);
    }

    return rc;
}

int data_pool_put(data_pool_t *pool, const char *key, json_t *value) {
    return data_pool_put_with_timestamp(pool, key, value, time(NULL));
}

int data_pool_put_with_timestamp(data_pool_t *pool, const char *key, json_t *value, time_t timestamp) {
    if (!pool || !key || !value) {
        return ERROR_INVALID_PARAM;
    }

    pthread_rwlock_wrlock(&pool->rwlock);

    if (pool->current_size >= pool->max_size) {
        pthread_rwlock_unlock(&pool->rwlock);
        return ERROR_MEMORY_ALLOC;
    }

    data_item_t *item = NULL;
    HASH_FIND_STR(pool->hash_table, key, item);

    if (item) {
        // 更新现有项
        json_decref(item->value);
        item->value = json_incref(value);
        item->timestamp = timestamp;
    } else {
        // 创建新项
        item = malloc(sizeof(data_item_t));
        if (!item) {
            pthread_rwlock_unlock(&pool->rwlock);
            return ERROR_MEMORY_ALLOC;
        }

        item->key = strdup(key);
        item->value = json_incref(value);
        item->timestamp = timestamp;

        HASH_ADD_STR(pool->hash_table, key, item);
        pool->current_size++;
    }

    pthread_rwlock_unlock(&pool->rwlock);

    // 如果启用了数据库持久化，保存到数据库
    if (pool->persist_to_db && pool->db_mgr) {
        db_datapool_set(pool->db_mgr, key, value);

        // 发送数据库更新事件
        if (pool->event_loop) {
            char *key_copy = strdup(key);
            event_t *event = event_create(EVENT_DB_UPDATE, key_copy, strlen(key_copy) + 1, free);
            if (event) {
                event_loop_send_event(pool->event_loop, event);
                event_destroy(event);
            }
        }
    }

    // 发送数据更新事件
    if (pool->event_loop) {
        char *key_copy = strdup(key);
        event_t *event = event_create(EVENT_DATA_UPDATE, key_copy, strlen(key_copy) + 1, free);
        if (event) {
            event_loop_send_event(pool->event_loop, event);
            event_destroy(event);
        }
    }

    return SUCCESS;
}

// 其他数据池函数实现...
